/*
 * Copyright 2008 Carnegie Mellon University
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package edu.cmu.lti.sepia.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class WrapperUtil {
	
	public static String execute(String command, String text, String enc) {
		Process process=null;
	    PrintWriter writer=null;
	    BufferedReader reader=null;
	    StringBuffer processed=new StringBuffer();

	    try{
			process=Runtime.getRuntime().exec(command,null,new File("./"));
			
			writer=new PrintWriter(new OutputStreamWriter(process.getOutputStream(),enc));
			writer.println(text);
			writer.close();

			reader=new BufferedReader(new InputStreamReader(process.getInputStream(),enc));
			
			String line="";
			while((line=reader.readLine())!=null){
				processed.append(line+"\n");
			}
			reader.close();
			process.destroy();
		}catch(Exception e){
			e.printStackTrace();
		}
	    
		if(processed==null){
			System.err.println("WARNING: Cannot get the result.");
			return text;
		}else{
			return processed.toString();
	    }
	}
	
	public static String execute( String command, String args, String[] text, int splitSize ) {
		StringBuilder sb = new StringBuilder();
		
		List<String> q = new ArrayList<String>();
		List<String[]> queue = new ArrayList<String[]>(); 
		for ( int i=0; i<text.length; i++ ) {
			q.add( text[i] );
			if ( i%splitSize==(splitSize-1) ) {
				queue.add( (String[]) q.toArray(new String[q.size()]) );
				q = new ArrayList<String>();
			}
		}
		if ( q.size()>0 ) {
			queue.add( (String[]) q.toArray(new String[q.size()]) );
		}
		
		for ( String[] miniText : queue ) {
			sb.append( execute( command, args, miniText ) );
		}
		return sb.toString();
	}
	
	public static String execute(String command, String args, String[] text) {
        String enc = "utf-8";
        Process process=null;
	    PrintWriter writer=null;
	    BufferedReader stdOutReader=null;
	    BufferedReader stdErrReader=null;
	    StringBuffer processed=new StringBuffer();
	
	    try{                                                   
	        process=Runtime.getRuntime().exec(command+" "+args,null,new File("./"));
	
	        writer=new PrintWriter(new OutputStreamWriter(process.getOutputStream(),enc));
	        stdOutReader = new BufferedReader(new InputStreamReader(process.getInputStream(),enc));
	        stdErrReader = new BufferedReader(new InputStreamReader(process.getErrorStream(),enc));
	
	        String line="";
            StringBuilder s = new StringBuilder();
            for ( String in : text ) {
            	s.append(in+"\n");
            }
            writer.println( s.toString()+"\n" );
            writer.flush();
            process.waitFor();
            while ((line = stdErrReader.readLine())!=null){
            }
            while ((line = stdOutReader.readLine())!=null){
            	processed.append(line+"\n");
            }
            writer.close();
            stdOutReader.close();
            stdErrReader.close();
            process.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        	try {
        		writer.close();
                stdOutReader.close();
                stdErrReader.close();
                process.destroy();
        	} catch (Exception e) {
        		e.printStackTrace();
        	}
        }

        if(processed==null){
                System.err.println("WARNING: Cannot get the result.");
                return "";
        }else{
                return processed.toString();
        }
	}
	
	public static String execute(String command, String text) {
		return execute( command, text, "utf-8" );
	}
	
	public static String execute( String command ) {
		Runtime runtime = null;
		Process process = null;
		InputStream is = null;
	    BufferedReader br = null;
		StringBuffer output = new StringBuffer();
		try {
			runtime = Runtime.getRuntime();
            process = runtime.exec( command );
			is = process.getInputStream();
			br = new BufferedReader(new InputStreamReader(is));  
			String line = null;
			while ((line = br.readLine()) != null) {
				output.append(line+"\n");
			}
			br.close();
			is.close();
			process.destroy();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return output.toString();
	}
}
